package com.martin.lib_base.binding.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.martin.lib_base.R
import dev.utils.app.info.KeyValue
import dev.utils.common.ReflectUtils

class SpinnerHintAdapter<T>(context: Context, resource: Int, objects: List<T>) :
    ArrayAdapter<T>(context, resource, objects) {

    override fun getCount(): Int {
        val count = super.getCount()
        return if (count == 0) 0 else count - 1
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = super.getView(position, convertView, parent)
        (view as TextView).setTextColor(
            if (position == count) {
                context.resources.getColor(R.color.text_gray_l)
            } else {
                context.resources.getColor(R.color.text_normal)
            }
        )
        return view
    }
}

@BindingAdapter("items", "hint", "itemId", requireAll = false)
fun bindAdapter(
    spinner: Spinner,
    items: List<KeyValue>?,
    hint: String? = null,
    itemId: Int? = null
) {
    val layoutId = itemId ?: R.layout.item_spinner_list
    if (items == null && hint.isNullOrEmpty()) {
        return
    }
    val list = items?.map { it.key } ?: listOf()
    if (hint.isNullOrEmpty()) {
        val adapter = ArrayAdapter(spinner.context, layoutId, list)
        spinner.adapter = adapter
    } else {
        val containHintList = list + hint
        val adapter = SpinnerHintAdapter(spinner.context, layoutId, containHintList)
        spinner.adapter = adapter
        spinner.setSelection(list.size)
    }
}

@BindingAdapter("selectedItem")
fun setSelectedItem(spinner: Spinner, item: String) {
    spinner.adapter?.let {
        val list = ReflectUtils.reflect(it).field("mObjects").get() as List<String>
        val index = list.indexOf(item)
        if (index >= 0) {
            spinner.setSelection(index)
        }
    }
}

@BindingAdapter("onSelected")
fun bindOnSelected(spinner: Spinner, callBack: (Int) -> Unit) {
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {
            callBack(position)
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }
}
